<?php

/**
 *
 * 版权所有：恰维网络<qwadmin.qiawei.com>
 * 作    者：寒川<hanchuan@qiawei.com>
 * 日    期：2016-01-20
 * 版    本：1.0.0
 * 功能说明：用户控制器。
 *
 * */

namespace Qwadmin\Controller;

//use Common\Controller\openerp;

class PurchController extends ComController {
    /*
     * 商品列表
     */

    function __construct() {
        parent::__construct();
    }

    public function index() {

       $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $m = M('purchorder');
        $sh['poname'] = I('get.poname');
        $sh['supplier'] = I('get.supplier');
        $sh['buyer_name'] = I('get.buyer_name');
        $sh['trade_pattern'] = I('get.trade_pattern');
        $sh['ebpCode'] = I('get.ebpCode');
        $where = array();

        if ($sh['buyer_name'] && !empty($sh['buyer_name'])) {
            $where['buyer_name'] = array('like', $sh['buyer_name']);
        }
        if ($sh['poname'] && !empty($sh['poname'])) {
            $where['poname'] = array('eq', $sh['poname']);
        }
        if ($sh['channel_code'] && !empty($sh['channel_code'])) {
            $where['channel_code'] = array('eq', $sh['channel_code']);
        }
        if ($sh['trade_pattern'] && !empty($sh['trade_pattern'])) {
            $where['trade_pattern'] = array('eq', $sh['trade_pattern']);
        }
        if ($sh['ebpCode'] && !empty($sh['ebpCode'])) {
            $where['ebpCode'] = array('eq', $sh['ebpCode']);
        }


        $pagesize = 20; #每页数量
        $offset = $pagesize * ($p - 1); //计算记录偏移量
        $count = $m->where($where)->count();
        $list = $m->where($where)->limit($offset . ',' . $pagesize)->order("ptime desc")->select();
        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $supplierlist = $m->field("supplier")->group('supplier')->cache(200)->select();
        $operlist = $m->field("oper")->group('oper')->cache(204)->select();
        $trade_typelist = $m->field("trade_type")->group('trade_type')->cache(204)->select();
        $this->assign('list', $list);
        $this->assign('channel_codelist', $channel_codelist);
        $this->assign('trade_patternlist', $trade_patternlist);
        $this->assign('ebpCodelist', $ebpCodelist);
        $this->assign('page', $page);
        $this->assign('sh', $sh);

        $this->display();
    }

    /***
     * 
     * 订单详情
     */
    function detail(){
        $ref=I("get.poname","0");
        if(!$ref){
            $this->error("参数错误",U("index"));
        }
        $m=D("purchorder");
        $res=$m->where(array('poname'=>$ref))->find();
//        dump($res);
        $this->assign("val",$res);
        $this->display();
    }
    /*
     * 商品添加
     */

    public function add() {

        $country = M('country')->where(array('enabled' => 'true'))->field('country_id,code,Chinese_name')->order("code asc")->cache(true)->select();

        $tradeList = M("Trade")->group('code')->cache(true)->select();
        foreach($tradeList as $key=>$tradeLis){
            $tradeList[$key]['code']=  strtolower($tradeLis['code']);
        }

        $this->assign('country', $country);
        $this->assign('tradeList', $tradeList);



        $this->display('form');
    }

    public function update() {

     $data=I("post.arr");

     $order=array();
	$order['poname']=$data['poname'];
	$order['desc']=$data['desc'];
	$order['ptime']=strtotime($data['ptime']);
	$order['supplier']=$data['supplier']; //需要转换
	$order['pick_id']=0;
	$order['trade_type']=$data['trade_type'];
	$order['courty']=$data['courty'];
	$order['untax_amount']=round($data['untax_amount']/$data['currency_rate'],2);
	$order['amount']=round($data['amount_untaxed']/$data['currency_rate'],2); ///转换为本币金额
	$order['curr']=$data['curr'];
	$order['curr_rate']=$data['curr_rate'];
	$order['state']=$data['state'];
	$order['compay']=$data['compay']; ///采购企业
	$order['flag']=0;
	$order['from_flag']=$data['from_flag'];
	$order['oper']=$this->USER['user'];
        
        $lines=$data['line'];
        
        foreach($lines['sku'] as $key=>$value){
            $line=array();
            
            $line['hash']=  md5($order['from_flag'].uniqid().$value);
            $line['poname']= $order['poname'];
            $line['sku']= $value;
            $line['name']= $lines['name'][$key];
            $line['earn13']= $lines['earn13'][$key];
            $line['lstprice']= $lines['lstprice'][$key];
            $line['locprice']= $lines['locprice'][$key];
            $line['num']= $lines['num'][$key];
            $line['date_purch']= $order['ptime'];
            
            
            $order['line'][$key]= $line;
        }
//        echo "<pre>";print_r($order);die;
        if(addpurchorder($order, $msg)){
            $this->success('操作成功！', U('index'));
        }
        else{
            $this->error("操作失败".$msg);
        }
      
    }

    /*
     * 商品编辑
     */

    public function edit($id = 0) {
        if(!$id){
            $this->error('参数错误！');
        }
        $m = M('purchorder');
        $mline = M('purchorder_line');
        $goods = $m->where("poname='$id'")->find();
        if (!$goods) {
            $this->error('参数错误！');
        }
        $linse = $mline->where("poname='$id'")->select();
        
        $goods['line']=$linse;
       $country = M('country')->where(array('enabled' => 'true'))->field('country_id,code,Chinese_name')->order("code asc")->cache(true)->select();

        $tradeList = M("Trade")->group('code')->cache(true)->select();
        foreach($tradeList as $key=>$tradeLis){
            $tradeList[$key]['code']=  strtolower($tradeLis['code']);
        }

        $this->assign('country', $country);
        $this->assign('goods', $goods);
        $this->assign('tradeList', $tradeList);
//        echo "<pre>";print_r($goods);die;
        $this->display('form');
    }

    public function del() {
        $ids = isset($_REQUEST['ids']) ? $_REQUEST['ids'] : false;

        if (is_array($ids)) {
            foreach ($ids as $k => $v) {
                $ids[$k] = intval($v);
            }
            if (!$ids) {
                $this->error('参数错误！');
                $uids = implode(',', $uids);
            }
        }

        $map['id'] = array('in', $ids);
        if (M('goods')->where($map)->delete()) {
            addlog('删除商品ID：' . $ids);
            $this->success('恭喜，商品删除成功！');
        } else {
            $this->error('参数错误！');
        }
    }

    /*
     * 商品的批处理相关
     */

    function goodsBath() {
        $ids = I("post.ids");
        $siteids = I("post.siteids");
        $storeids = I("post.storeids", 0);
        $optype = I("post.optype", ADD_NEW);
//        var_dump($optype);die;
        $jumpUrl = $_SERVER['HTTP_REFERER'];
        if (empty($ids) || !$ids) {
            $this->error("商品为空，请选择要操作的商品");
        }
        if (empty($siteids) || !$siteids) {
            $this->error("站点为空，请选择要操作的站点");
        }
//        if (empty($storeids) || !$storeids) {
//            $this->error("店铺为空，请选择要操作的店铺");
//        }

        $data = array();
        foreach ($ids as $key => $goods_id) {
            foreach ($siteids as $sk => $svalue) {
                $tempdata['goods_id'] = $goods_id;
                $tempdata['site_id'] = $svalue;
                $tempdata['op'] = $optype;
                $tempdata['uid'] = $this->USER['uid'];
                $tempdata['store_id'] = $storeids;
                $tempdata['optime'] = time();
                $data[] = $tempdata;
            }
        }
//        var_dump($data);die;
        $opModel = M("Goods_op");
        $opModel->startTrans();
        foreach ($data as $goodsdata) {
            $where['goods_id'] = $goodsdata['goods_id'];
            $where['site_id'] = $goodsdata['site_id'];
            $where['op'] = $goodsdata['op'];
//            $where['store_id'] = $goodsdata['store_id'];
            $hasid = $opModel->where($where)->getField("id");
            if ($hasid) {
                $updata = $goodsdata;
                $updata['rsp'] = '';
                $flag = $opModel->where(array("id" => $hasid))->save($updata);
            } else {
                $flag = $opModel->add($goodsdata);
            }

            if (!$flag) {
                $opModel->rollback();
                $this->error("操作失败，请重试", $jumpUrl);
            }
        }
        $opModel->commit();
        $this->success("操作成功", $jumpUrl);
    }
    
    function checkpo(){
        $return=array('status'=>0,'msg'=>"");
        $name=I("post.name","");
        if(empty($name)){
            $return['msg']="名称不能为空";
            $this->ajaxReturn($return);
        }
        $data=M("purchorder")->field("poname")->where(array("poname"=>$name))->find();
        if($data){
            $return['msg']="批次名已存在，请重新更换再试！";
            $this->ajaxReturn($return);
        }
        
        $return['msg']="名称可以使用";
        $return['status']=1;
        $this->ajaxReturn($return);
    }

    function getskuinfo() {
        $return=array('status'=>0,'msg'=>"");
        $sku=I("post.sku");
        if(empty($sku)){
            $return['msg']="sku为空";
            $this->ajaxReturn($return);
        }
        $goodsModel=M("goods");
        $data=$goodsModel->where(array('sku'=>$sku))->find();
        if($data){
            $return['data']=$data;
            $return['status']=1;
            $this->ajaxReturn($return);
        }
        
    }
}
